package mybatisplus.spring.boot.admin.common.util;

import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.po.TableFill;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

/**
 * 演示例子，执行 main 方法控制台输入模块表名回车自动生成对应项目目录中
 */
public class CodeGenerator {

    /**
     * <p>
     * 读取控制台内容
     * </p>
     */
    private static String scanner(String tip) {
        Scanner scanner = new Scanner(System.in);
        StringBuilder help = new StringBuilder();
        help.append("请输入" + tip + "：");
        System.out.println(help.toString());
        if (scanner.hasNext()) {
            String ipt = scanner.next();
            if (StringUtils.isNotEmpty(ipt)) {
                return ipt;
            }
        }
        throw new MybatisPlusException("请输入正确的" + tip + "！");
    }

    private static GlobalConfig getGlobalConfig(Class objectClass){
        // 全局配置
        GlobalConfig gc = new GlobalConfig();
        String projectPath = objectClass.getResource("/").getPath().replaceAll("/target/(test-)?classes/", "");
        gc.setOutputDir(projectPath + "/src/main/java");
        gc.setAuthor("AutoGenerator");
        gc.setOpen(false);
        gc.setFileOverride(true);
        gc.setIdType(IdType.ID_WORKER_STR);
        return gc;
    }

    private static DataSourceConfig getDataSourceConfig(){
        // 数据源配置
        DataSourceConfig dsc = new DataSourceConfig();
        dsc.setUrl("jdbc:mysql://152.136.54.4:3306/demo?useUnicode=true&characterEncoding=UTF-8&allowMultiQueries=true");
        dsc.setDriverName("com.mysql.jdbc.Driver");
        dsc.setUsername("root");
        dsc.setPassword("123456");
        return dsc;
    }

    private static PackageConfig getPackageConfig(String packageName){
        // 包配置
        PackageConfig pc = new PackageConfig();
        pc.setModuleName(scanner("模块名"));
        pc.setParent(packageName);
        return pc;
    }

    private static InjectionConfig getInjectionConfig(Class objectClass,AutoGenerator autoGenerator){
        InjectionConfig cfg = new InjectionConfig() {
            @Override
            public void initMap() {
                // to do nothing
            }
        };
        List<FileOutConfig> focList = new ArrayList<>();
        focList.add(new FileOutConfig("/templates/mapper.xml.ftl") {
            @Override
            public String outputFile(TableInfo tableInfo) {
                String projectPath = objectClass.getResource("/").getPath().replaceAll("/target/(test-)?classes/", "");
                // 自定义输入文件名称
                return projectPath + "/src/main/resources/mapper/" + autoGenerator.getPackageInfo().getModuleName()
                        + "/" + tableInfo.getEntityName() + "Mapper.xml";
            }
        });
        cfg.setFileOutConfigList(focList);
        return cfg;
    }

    private static StrategyConfig getStrategyConfig(){
        StrategyConfig strategy = new StrategyConfig();
        strategy.setNaming(NamingStrategy.underline_to_camel);
        strategy.setColumnNaming(NamingStrategy.underline_to_camel);
        strategy.setEntityLombokModel(true);
        strategy.setRestControllerStyle(true);
        String tables = scanner("表名：");
        List<TableFill> fillList = new ArrayList<>();
        fillList.add(new TableFill("create_time", FieldFill.INSERT));
        fillList.add(new TableFill("update_time", FieldFill.UPDATE));
        strategy.setTableFillList(fillList);
        strategy.setInclude(tables.trim().split(","));
        strategy.setControllerMappingHyphenStyle(true);
        strategy.setTablePrefix("t_","s_");
        return strategy;
    }

    public static void generatorCustomDirectory(Object object,String packageName,AutoGenerator autoGenerator){
        String projectPath = object.getClass().getResource("/").getPath().replaceAll("/target/(test-)?classes/", "");
        String outputDir = projectPath + "/src/main/java/"+packageName.replaceAll("\\.","/");

        try {
            File facadeOutputDirFile = new File(outputDir + "/facade");
            if (!facadeOutputDirFile.exists()) {
                facadeOutputDirFile.mkdir();
            }
            File integrationOutputDirFile = new File(outputDir + "/integration");
            if (!integrationOutputDirFile.exists()) {
                integrationOutputDirFile.mkdir();
            }

            File moduleOutputDirFile = new File(outputDir + "/" + autoGenerator.getPackageInfo().getModuleName());
            if (!moduleOutputDirFile.exists()) {
                moduleOutputDirFile.mkdir();
            }
            File boModuleOutputDirFile = new File(moduleOutputDirFile.getPath() + "/bo");
            if (!boModuleOutputDirFile.exists()) {
                boModuleOutputDirFile.mkdir();
            }
            File voModuleOutputDirFile = new File(moduleOutputDirFile.getPath() + "/vo");
            if (!voModuleOutputDirFile.exists()) {
                voModuleOutputDirFile.mkdir();
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    public static void codeAutoGenerator(Object object,String packageName){
        // 代码生成器
        AutoGenerator autoGenerator = new AutoGenerator();

        // 全局配置
        autoGenerator.setGlobalConfig(getGlobalConfig(object.getClass()));

        // 数据源配置
        autoGenerator.setDataSource(getDataSourceConfig());

        // 包配置
        autoGenerator.setPackageInfo(getPackageConfig(packageName));

        // 自定义配置
        autoGenerator.setCfg(getInjectionConfig(object.getClass(),autoGenerator));

        //模板
        autoGenerator.setTemplate(new TemplateConfig().setXml(null));

        // 策略配置
        autoGenerator.setStrategy(getStrategyConfig());

        //模板引擎
        autoGenerator.setTemplateEngine(new FreemarkerTemplateEngine());

        autoGenerator.execute();

        //生成自定义目录
        generatorCustomDirectory(object,packageName,autoGenerator);
    }
}